from sqlalchemy import Column, Integer, String, Text, DateTime, Boolean, ForeignKey, Enum
from sqlalchemy.orm import relationship
from sqlalchemy.sql import func
from app.core.database import Base
import enum

# 消息类型枚举
class MessageType(enum.Enum):
    USER_TO_ADMIN = "user_to_admin"      # 用户发给管理员
    ADMIN_TO_USER = "admin_to_user"      # 管理员发给用户
    SYSTEM = "system"                    # 系统消息

# 消息状态枚举
class MessageStatus(enum.Enum):
    UNREAD = "unread"                    # 未读
    READ = "read"                        # 已读
    REPLIED = "replied"                  # 已回复

# 消息数据模型
class Message(Base):
    # 数据库表名
    __tablename__ = "messages"
    
    # 消息ID，主键，自增
    id = Column(Integer, primary_key=True, index=True)
    # 发送者ID
    sender_id = Column(Integer, ForeignKey("users.id"), nullable=False)
    # 接收者ID
    receiver_id = Column(Integer, ForeignKey("users.id"), nullable=False)
    # 消息标题
    title = Column(String(255), nullable=False)
    # 消息内容
    content = Column(Text, nullable=False)
    # 消息类型
    message_type = Column(Enum(MessageType), nullable=False)
    # 消息状态
    status = Column(Enum(MessageStatus), default=MessageStatus.UNREAD)
    # 父消息ID（用于回复功能）
    parent_id = Column(Integer, ForeignKey("messages.id"), nullable=True)
    # 是否删除（软删除）
    is_deleted = Column(Boolean, default=False)
    # 创建时间
    created_at = Column(DateTime(timezone=True), server_default=func.now())
    # 更新时间
    updated_at = Column(DateTime(timezone=True), onupdate=func.now())
    # 阅读时间
    read_at = Column(DateTime(timezone=True), nullable=True)
    
    # 关联关系
    sender = relationship("User", foreign_keys=[sender_id], backref="sent_messages")
    receiver = relationship("User", foreign_keys=[receiver_id], backref="received_messages")
    parent = relationship("Message", remote_side=[id], backref="replies")